#! /usr/bin/env python3

import os
import re

usertool = "./dpdk-devbind.py"
# nic_cards = ["\"Virtio network device 1000\"","\"82599ES 10-Gigabit SFI/SFP+ Network Connection 10fb\""]
nic_cards = ["\"82599ES 10-Gigabit SFI/SFP+ Network Connection 10fb\""]


def scan_nic_cards():
    pcino = []
    nicname = []
    for nic_card in nic_cards:
        command_1 = usertool + " --status | grep " + nic_card
        results = os.popen(command_1).readlines()
        print(results)
        for result in results:        
            pci = re.search(r'([0-9]|[a-f]){4}:([0-9]|[a-f]){2}:([0-9]|[a-f]){2}.([0-9]|[a-f])', result)
            name = re.search(r'ens[0-9]+', result)
            if pci != None:
                pcino.append(pci.group())
            if name != None:
                nicname.append(name.group())
    return  pcino, nicname

def dpdk_config():
    print("===Welcome to DPDK Config Script===")
    print("         Author: Chengmin          ")

    print("===================================")
    print("Step 0: Check root user")
    results = os.popen("whoami").readlines()
    if (len(results) == 0) | (results[0] != "root\n"):
        print("Not a root user, bye!")
        return
    
    print("===================================")
    print("Step 1: Scan all nic_card.")
    pcino, nicname = scan_nic_cards()

    print("===================================")
    print("Step 2: Shutdown the nic cards.")
    print("pci no: " + str(pcino))
    print("dev name (using kernel): " + str(nicname))
    command = ""
    for devname in nicname:
        command += "ifconfig " + devname + " down\n" 

    print("===================================")
    print("Step 3: Modprobe vfio no-iommu")
    command += "modprobe vfio-pci\n"
    command += "modprobe vfio enable_unsafe_noiommu_mode=1\n"
    command += "echo 1 > /sys/module/vfio/parameters/enable_unsafe_noiommu_mode\n"
    
    print("===================================")
    print("Step 4: Alloc hugepages for all devs")
    print("1024 x 2048kB size, total " + str(len(pcino)) + " devs")
    size = 1024
    command += "echo " + str(size) + " > /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages\n"

    print("===================================")
    print("Step 5: Bind nic card with vfio-pci")
    for pci in pcino:
        command += usertool + " -b vfio-pci " + pci + "\n"

    print("===================================")
    print("Step 6: Display DPDK dev status")
    command += usertool + " -s\n"
    os.system(command)


if __name__ == "__main__":
    dpdk_config()

